<?php

/**
 * @author  spring
 * @version 2014-6-7 上午9:55:01
 */
class  Basic
{
    const  INSERT = "insert";
    const  UPDATE = "update";
    const  DELETE = "delete";

    /**
     * Description 判断是否是post请求
     * @param field_type  bare_field_name
     * @return boolean
     */
    public static function is_post()
    {
        $method = $_SERVER['REQUEST_METHOD'];
        if($method=='POST'){
            return TRUE;
        }else{
            return FALSE;
        }
    }

    //弹框
    /**
     * Description
     * @param        field_type  bare_field_name
     * @param String $msg        弹框提示的内容
     * @param string $url        弹框弹出后跳转的页面
     */
    public static function alert($msg,$url = NULL)
    {
        header("Content-type: text/html; charset=utf-8");
        $alert_msg = "alert('$msg');";
        if(empty($url)){
            $gourl = 'history.go(-1);';
        }else{
            $gourl = "window.location.href = '{$url}'";
        }
        echo "<script>$alert_msg $gourl</script>";
        exit;
    }

    /**
     * Description 获取所有统计的数量
     * @param                       field_type  bare_field_name
     * @param Kohana_Database_Query $pre        DB操作数据库的返回
     * @return int 数量
     */
    public static function getTotle($pre)
    {//echo $pre->compile('newerp');exit;
        return $pre->execute('newerp')
            ->get('totle',0);
    }

    /**
     * Description 获取所有统计的数量
     * @param                       field_type  bare_field_name
     * @param Kohana_Database_Query $pre        DB操作数据库的返回
     * @return int 数量
     */
    public static function getallTotle($pre)
    {
        return $pre->execute('newerp')
            ->current();
    }

    public static function getallcountTotle($pre)
    {
        return $pre->execute('newerp')
            ->as_array();
    }

    /**
     * Description   获取所有查询结果
     * @param                       field_type      bare_field_name
     * @param int                   $items_per_page 分页时每页的条数
     * @param int                   $offset         分页的偏移量
     * @param Kohana_Database_Query $pre            DB操作数据库的返回
     * @return array 返回查询结果
     */
    public static function getList($items_per_page,$offset,$pre) {
        $export_tax_rebate   = Kohana::$config->load('export_tax_rebate')->as_array();
        $enterprise_dominants = Kohana::$config->load('enterprise_dominant')->as_array();
        $warehouse = Kohana::$config->load('vmi_warehouse')->as_array();
        //$warehouse_id = Kohana::$config->load('warehouse')->warehouse_id;

        $datas = $pre->limit($items_per_page)->offset($offset)->execute('newerp')->as_array();

        //20160712 倪瑞添加 sku储位查询
        foreach ($datas as &$data) {
            /*$sql="SELECT id,place
              FROM skusystem_places 
              WHERE id= ANY(
                  SELECT place_id 
                  FROM skusystem_place_skus 
                  WHERE isavailable=1 
                  AND sku='".$data['sku']."') 
              AND warehouse_id={$warehouse_id}";*/
            //$sql="SELECT place FROM skusystem_places WHERE id=ANY(SELECT place_id FROM skusystem_place_skus WHERE isavailable=1 AND sku='".$data['sku']."')";
            /*$data['storage_position']=DB::query(Database::SELECT,$sql)
                ->execute('newerp')->get('place');*/
            $data['warehouseid'] = $warehouse[$data['warehouseid']];
            $data['export_tax_rebate'] = $export_tax_rebate[$data['export_tax_rebate']];
            $data['enterprise_dominant'] = $enterprise_dominants[$data['enterprise_dominant']];
        }
        return $datas;
    }


    /**
     * Description 获取所有统计的数量预处理
     * @param string $tablename 表名
     * @return Kohana_Database_Query    DB操作数据库的返回
     */
    public static function getTotlePre($tablename)
    {
        return DB::select(DB::expr('COUNT(id)AS totle'))
            ->from($tablename);
    }


    /**
     * Description 获取所有统计的数量预处理
     * @param string $tablename 表名
     * @return Kohana_Database_Query    DB操作数据库的返回
     */
    public static function getTotleallPre($tablename)
    {
        if($tablename=='warehouseorders'){
            $quantity = 'warehouse_quantity';
        }else{
            $quantity = 'quantity';
        }
        return DB::select(DB::expr('SUM('.$quantity.')AS num'),DB::expr('SUM(money)AS money'),DB::expr('SUM(cost)AS cost'))
            ->from($tablename);
    }

    /**
     * Description 获取所有统计的结果预处理
     * @param string $tablename 表名
     * @return Kohana_Database_Query    DB操作数据库的返回
     */
    public static function getListPre($tablename)
    {
        return DB::select()
            ->from($tablename);
    }

    public static function getListPre1($tablename)
    {
        return DB::select('sku','sku_name','storage_position','single_price',DB::expr('SUM(quantity)AS quantity'),DB::expr('SUM(money)AS money'),DB::expr('SUM(cost)AS cost'))
            ->from($tablename);
    }

    public static function getListPre2($tablename)
    {
        return DB::select('sku','sku_name','storage_position','single_price','supplier_id',DB::expr('SUM(warehouse_quantity)AS quantity'),DB::expr('SUM(money)AS money'),DB::expr('SUM(cost)AS cost'))
            ->from($tablename);
    }

    /**
     * Description DB处理的条件简单封装
     * @param                       field_type  bare_field_name
     * @param Kohana_Database_Query $pre        DB操作数据库的返回
     * @param array                 $condition  and_where 方法的处理条件
     * @return Kohana_Database_Query  DB操作数据库的返回
     */
    public static function condition($pre,$condition)
    {
        return $pre->and_where($condition[0],$condition[1],$condition[2]);
    }

    public static function condition1($pre,$condition)
    {
        return $pre->and_having($condition[0],$condition[1],$condition[2]);
    }

    /**
     * Description 获取说有供应商的id拼接字符串
     * @return string   ["伟创模型科技有限公司","深圳力宝激光","深圳市俊进电子有限公司"]
     */
    public static function  getallsupp($name)
    {
        //START     ----------------------------------CWY更新代码-------------------------------------
        $suppliers = Newerpclientapi::getSupplierByName($name);
        $results   = array();
        foreach($suppliers as $supplier){
            $str       = trim($supplier['name']);
            $results[] = array('label' => $str);
        }
//        $suppliers = DB::select('vProviderName')
//            ->from('erp_provider')
//            ->where('vProviderName','like','%'.$name.'%')
//            ->limit(15)
//            ->execute('readonlyerp')
//            ->as_array();
//        $results   = array();
//        foreach($suppliers as $supplier){
//            $str       = trim($supplier['vProviderName']);
//            $results[] = array('label' => $str);
//        }
        //END     ----------------------------------CWY更新代码-------------------------------------
        return $results;
    }

    /**
     * Description 根据供应商name获取id
     * @return int   供应商id
     */
    public static function  getidByName($name)
    {
        //START     ----------------------------------CWY更新代码-------------------------------------
        /**
         * 根据供应商名称模糊查询一个供应商的id,获取不到默认值为1
         */
        $suppliers =  supplierskus::getSuppliers(array('id'),array('name' => "like '%$name%'"));
        if($suppliers){
            $supplier_id = $suppliers[0]['id'];
        }else{
            $supplier_id = 1;
        }
        //   	$supplier_id=DB::select('id')->from('erp_provider')
        //        ->where('vProviderName','like','%'.$name.'%')->execute('readonlyerp')->get('id',1);
        //END       ----------------------------------CWY更新代码-------------------------------------
        return $supplier_id;
    }

    /**
     * Description 根据供应商id获取name
     * @return name   供应商name
     */
    public static function  getnameByid($id)
    {
        //START     ----------------------------------CWY更新代码-------------------------------------
        /**
         * 根据供应商id获取供应商名称,获取不到默认值为0
         */
        $supplier = supplierskus::getSuppliers(array('name'),array('id' => "=$id"));
        if($supplier){
            $vProviderName = $supplier[0]['name'];
        }else{
            $vProviderName = 0;
        }
        //   	$vProviderName=DB::select('vProviderName')->from('erp_provider')
        //        ->where('id','=',$id)->execute('readonlyerp')->get('vProviderName', 0);
        //END     ----------------------------------CWY更新代码-------------------------------------
        return $vProviderName;
    }

    /**
     * Description 操作数据库判断sku是否存在
     * @param        field_type  bare_field_name
     * @param String $sku
     * @return  $id  产品id
     */
    public static function check_sku($sku)
    {
        //START     ----------------------------------CWY更新代码-------------------------------------
        /**
         * 根据sku查询产品id
         */
        $sku = Skusystemapi::getSku($sku);
        if($sku){
            $id = $sku['id'];
        }else{
            $id = 0;
        }
        //       $id=DB::select('products_id')->from('erp_products_data')
        //        ->where('products_sku','=',$sku)->execute('readonlyerp')->get('products_id',0);
        //END      ----------------------------------CWY更新代码-------------------------------------
        return $id;
    }

    /**
     * Description 根据sku返回规格
     * @param        field_type  bare_field_name
     * @param String $sku
     * @return  array  产品规格信息
     */
    public static function load_sku_info($sku, $warehouseid)
    {
        //START     ----------------------------------CWY更新代码-------------------------------------
        $cnname  = Skusystemapi::getSkuCnname($sku);
        $place   = Skusystemapi::getSkuPlacesForVMI($sku, $warehouseid);
        $asprice = Skusystemapi::getSkuAsprice($sku);
        $price   = Skusystemapi::getSkuPrice($sku);

        $result['products_place']=isset($place)?$place:'';
        $result['products_name_cn']=isset($cnname[0]['name'])?$cnname[0]['name']:'';
        $result['size']='';
        $result['products_value']=isset($asprice[0]['num'])?$asprice[0]['num']:'';
        $result['products_values']=isset($price[0]['num'])?$price[0]['num']:'';

        //        $skuinfo = DB::select('products_name_cn','products_place','products_value','products_values')
        //            ->from('erp_products_data')
        //            ->where('products_sku','=',$sku)
        //            ->execute('readonlyerp')
        //            ->current();
        //        $result  = array(
        //            'products_place'   => $skuinfo['products_place']?$skuinfo['products_place']:'',
        //            'size'             => '',
        //            'products_name_cn' => $skuinfo['products_name_cn']?$skuinfo['products_name_cn']:'',
        //            'products_value'   => $skuinfo['products_value']?$skuinfo['products_value']:'',
        //            'products_values'  => $skuinfo['products_values']?$skuinfo['products_values']:''
        //        );
        //END     ----------------------------------CWY更新代码-------------------------------------
        return $result;
    }

    /**
     * 查询sku在售状态
     * @param $sku
     */
    public static function get_sku_status(array $sku = array())
    {
        if(!isset($sku) or empty($sku)){
            return;
        }
        //START     ----------------------------------CWY更新代码-------------------------------------
        $skuinfos = Skusystemapi::getSkuAndStatus($sku);
        if(empty($skuinfos)){
            return;
        }
        $re = array();
        foreach($skuinfos as $skuinfo){
            $re[$skuinfo['sku']]['status_id']     = $skuinfo['status_id'];
            $re[$skuinfo['sku']]['status_string'] = $skuinfo['status'];
        }
//        $skuinfos = DB::select(array(
//            DB::expr('upper(products_sku)'),
//            'sku'
//        ),'products_remark_2','status_name')
//            ->from('erp_products_data')
//            ->join('erp_status')
//            ->on('erp_products_data.products_remark_2','=','erp_status.object_status')
//            ->where('products_sku','in',$sku);
//        $skuinfos = $skuinfos->execute('readonlyerp')
//            ->as_array();
//
//        if(empty($skuinfos)){
//            return;
//        }
//
//        $re = array();
//        foreach($skuinfos as $skuinfo){
//            $re[$skuinfo['sku']]['status_id']     = $skuinfo['products_remark_2'];
//            $re[$skuinfo['sku']]['status_string'] = $skuinfo['status_name'];
//        }
        //END     ----------------------------------CWY更新代码-------------------------------------
        return $re;
    }

    //盘点那上传数据要
    public static function load_sku_info1($sku)
    {
        //START     ----------------------------------CWY更新代码-------------------------------------
        $cnname  = Skusystemapi::getSkuCnname($sku);
        $place   = Skusystemapi::getSkuPlace($sku);
        $asprice = Skusystemapi::getSkuAsprice($sku);
        $price   = Skusystemapi::getSkuPrice($sku);
        $result  = array(
            'storage_position' => isset($cnname[0]['place'])?$cnname[0]['place']:'',
            'sku_standard'     => '',
            'sku_name'         => isset($place[0]['name'])?$place[0]['name']:'',
            'products_value'   => isset($asprice[0]['num'])?$asprice[0]['num']:'',
            'products_values'  => isset($price[0]['num'])?$price[0]['num']:''
        );
//        $skuinfo = DB::select('products_name_cn','products_place','products_value','products_values')
//            ->from('erp_products_data')
//            ->where('products_sku','=',$sku)
//            ->execute('readonlyerp')
//            ->current();
//        $result  = array(
//            'storage_position' => $skuinfo['products_place']?$skuinfo['products_place']:'',
//            'sku_standard'     => '',
//            'sku_name'         => $skuinfo['products_name_cn']?$skuinfo['products_name_cn']:'',
//            'products_value'   => $skuinfo['products_value']?$skuinfo['products_value']:'',
//            'products_values'  => $skuinfo['products_values']?$skuinfo['products_values']:''
//        );
        //END     ----------------------------------CWY更新代码-------------------------------------
        return $result;
    }

    /**
     * Description 操作日志的公告方法
     * 用法 Basic::log(array('sku' =>$condition['sku'],'value'=>'特殊出库一条记录','type'=>Basic::INSERT,'controller'=>$this->request->controller(),'action'=>$this->request->action(),'table_name'=>'deliveryorders','table_id'=>$id));
     * @param       array      ('sku' =>'ss','value'=>'sss','type'=>Basic::INSERT,'controller'=>$this->request->controller(),'action'=>$this->request->action())
     * @param array $condition 条件
     */
    public static function  log($condition)
    {
        Log::info('sku[:sku] -- value[:value] -- userid [:userid] -- type[:type] -- controller[:controller] -- action[:action] -- table_name[:table_name] -- table_id[:table_id]',array(
            ':controller' => $condition['controller']?$condition['controller']:'',
            ':action'     => $condition['action']?$condition['action']:'',
            ':sku'        => $condition['sku']?$condition['sku']:'',
            ':value'      => $condition['value']?$condition['value']:'',
            ':userid'     => User::active_user()->id,
            ':type'       => $condition['type']?$condition['type']:'',
            ':table_name' => $condition['table_name']?$condition['table_name']:'',
            ':table_id'   => $condition['table_id']?$condition['table_id']:'',
        ));
    }

    /**
     * Description 获取特殊出库状态
     * @param field_type  bare_field_name
     * @return array 特殊出库状态
     */
    public static function get_delivery_status($table,$type)
    {
        return DB::select()
            ->from('statusdics')
            ->where('number','>','10')
            ->and_where('table','=',$table)
            ->and_where('colum_name','=',$type)
            ->execute('newerp')
            ->as_array();
    }


    /**
     * Description 获取特殊出库状态
     * @param field_type  bare_field_name
     * @return array 特殊出库状态
     */
    public static function get_alldelivery_status($table,$type)
    {
        return DB::select()
            ->from('statusdics')
            ->where('table','=',$table)
            ->and_where('colum_name','=',$type)
            ->execute('newerp')
            ->as_array();
    }

    /**
     * Description 根据name 找用户id
     * @param         field_type  bare_field_name
     * @param unknown $uname
     * @return Ambigous <mixed, unknown> 注释
     */
    public static function get_uid($uname)
    {
        return $user_id = DB::select('id')
            ->from('users')
            ->where('name','=',$uname)
            ->execute()
            ->get('id',0);
    }

    /**
     * Description 根据id找用户名字
     * @param         field_type  bare_field_name
     * @param unknown $id
     * @return Ambigous <mixed, unknown> 注释
     */
    public static function get_uname($id)
    {
        return $uname = DB::select('name')
            ->from('users')
            ->where('id','=',$id)
            ->execute()
            ->get('name',0);
    }


    public static function  checktime($time)
    {
        $config = Config::load('site');
        if(strtotime($config['close_bill'])>=strtotime($time)){
            return TRUE;
        }else{
            return FALSE;
        }
    }

    //获取退件批次号
    public static function  get_batches()
    {
        $batches  = ORM::factory('returned_batch')
            ->order_by('created','DESC')
            ->find_all()
            ->as_array();
        $batchstr = '';
        foreach($batches as $batch){
            $batchstr = $batchstr.'"'.$batch->batch_code.'"'.',';
        }
        return $batchstr;
    }

    //获取付款方式id及name
    public static function  get_pay_way()
    {
        $payway  = array();
        $sql_pay = "SELECT id,type FROM `erp_pay_type` WHERE 1";
        $pays    = DB::query(Database::SELECT,$sql_pay)
            ->execute('readonlyerp')
            ->as_array();
        foreach($pays as $pay){
            $payway[$pay['id']] = $pay['type'];
        }
        return $payway;
    }

    //获取订单详情表的所有状态
    public static function  get_podetail_status()
    {
        $status = array();
        $stas   = ORM::factory('statusdic')
            ->where('table','=','purchaseorder_details')
            ->where('colum_name','=','status')
            ->find_all()
            ->as_array();

        foreach($stas as $st){
            $status[$st->number] = $st->value;
        }
        return $status;
    }


    public static function get_warehouse_list() {
        return DB::select('store_name', 'ware_id')
            ->from('branch_stores')
            ->where('store_id', '=', 0)
            ->execute()
            ->as_array('ware_id', 'store_name');
    }
}
